package cn.shyouchi.wuguanjia.android.api;

import java.util.concurrent.TimeUnit;

import cn.shyouchi.wuguanjia.android.components.retrofit.YouChiConverterFactory;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * Created by Eenie on 2017/3/3 at 14:15
 * Email: 472279981@qq.com
 * Des:
 */

public class ClientProvider {
    public static final String BASE_URL = "http://118.178.88.132:8000/api/";
    private static final int DEFAULT_TIMEOUT = 100; //超时时间100秒
    private static ClientProvider mDefaultClient;

    public static ClientProvider getDefaultClient() {
        if (mDefaultClient == null) {
            synchronized (ClientProvider.class) {
                if (mDefaultClient == null) {
                    mDefaultClient = new ClientProvider();
                }
            }
        }
        return mDefaultClient;
    }

    public Retrofit getRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getOkHttpClient())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(YouChiConverterFactory.create())
                .build();
        return retrofit;
    }

    public Retrofit getRetrofit(UserStorage userStorage) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(getOkHttpClient(userStorage))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(YouChiConverterFactory.create())
                .build();
        return retrofit;
    }

    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        return builder.build();
    }

    private OkHttpClient getOkHttpClient(UserStorage userStorage) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new TokenInterceptor(userStorage));
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        return builder.build();
    }


}
